{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 递归\n",
    "看到代码好简单，让你自己写就一头蒙逼"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1. 计算斐波那契数列\n",
    "\n",
    "<img src=\"./fibonacci-spiral.gif\" />"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def recur_fibo(n):\n",
    "   \"\"\"递归函数\n",
    "   输出斐波那契数列，n=0则是0，n=1则是1，否则是前面两个数字的和\n",
    "   \"\"\"\n",
    "   if n <= 1:\n",
    "       return n\n",
    "   else:\n",
    "       return(recur_fibo(n-1) + recur_fibo(n-2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "55"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "recur_fibo(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. 使用递归-深度遍历二叉树\n",
    "\n",
    "<img src=\"./deep_visit_tree.png\" style=\"margin-left:0px; width:400px;\"/>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node(object):\n",
    "    def __init__(self, data, left=None, right=None):\n",
    "        self.data = data\n",
    "        self.left = left\n",
    "        self.right = right\n",
    "\n",
    "tree = Node(1, Node(3,  Node(7,  Node(0)), Node(6)), Node( 2,  Node(5),  Node(4) ))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def deep_visit(root):\n",
    "    \"\"\"深度遍历二叉树\"\"\"\n",
    "    if not root: return\n",
    "    print(root.data, end=\",\")\n",
    "    deep_visit(root.left)\n",
    "    deep_visit(root.right)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1,3,7,0,6,2,5,4,"
     ]
    }
   ],
   "source": [
    "deep_visit(tree)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
